// 将状态存在storage中
import { AppStorageCache } from '../utils/cache';
import { useEffect, useState } from 'react';

// 创建StorageState hook
const createStorageStateHook = (storageState) => (key, defaultVal) => {
    let initVal = defaultVal; // 初始值
    if (AppStorageCache.get(key, storageState) === null) {
        // 加入缓存
        if (defaultVal) {
            AppStorageCache.put(key, defaultVal, 24 * 60 * 60, storageState);
        }
    } else {
        initVal = AppStorageCache.get(key, storageState);
    }
    const [val, setVal] = useState(initVal);
    const saveVal = (newVal) => { // 保存值
        setVal(newVal);
        AppStorageCache.put(key, newVal, 24 * 60 * 60, storageState);
    };

    return [val, saveVal];
};

export const useLocalStorageState = createStorageStateHook(localStorage);
export const useSessionStorageState = createStorageStateHook(sessionStorage);
